package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.service.RoleService;
import com.ruitaowang.core.domain.Role;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色相关
 */
@RestController
public class APIRoleController extends BaseController {

    @Autowired
    private RoleService roleService;

    @RequestMapping(value = "/api/roles", method = RequestMethod.GET)
//    @RolesAllowed({"ROLE_roles:view", "ROLE_root"})
    public String list(Role role){
        List<Role> list;
        MsgOut o;
        list = roleService.select(role);
        o = MsgOut.success(list);

        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/roles", method = RequestMethod.POST)
//    @RolesAllowed({"ROLE_roles:create", "ROLE_root"})
    public String create(Role role){
        MsgOut o;
        List<Role> list = new ArrayList<>();
        LOGGER.debug(renderJson(role));
        roleService.insert(role);
        list.add(role);
        o = MsgOut.success(list);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/roles", method = RequestMethod.PUT)
//    @RolesAllowed({"ROLE_roles:update", "ROLE_root"})
    public String update(Role role){//@Valid
        roleService.update(role);
        return this.renderJson(MsgOut.success(role));
    }

    @RequestMapping(value = "/api/roles/{id}", method = RequestMethod.DELETE)
//    @RolesAllowed({"ROLE_roles:delete", "ROLE_root"})
    public String delete(@PathVariable("id") Long id){
        roleService.delete(id);
        return this.renderJson(MsgOut.success());
    }

}
